package com.sunrise.generico.util;

import java.util.Iterator;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.context.FacesContext;

public class MessagesUtil {
	private static ResourceBundle messageBundle = ResourceBundle.getBundle("messages");
	private static ResourceBundle resourceBundle = ResourceBundle.getBundle("resources");
	private static ResourceBundle infosBundle = ResourceBundle.getBundle("info");
	
	public static void addNewInfoMessage(String message) {
		addMessage(FacesMessage.SEVERITY_INFO, message, message);
	}
	
	public static void addNewAlertMessage(String message) {
		addMessage(FacesMessage.SEVERITY_WARN, message, message);
	}
	
	public static void addNewErrorMessage(String message, String details) {
		addMessage(FacesMessage.SEVERITY_ERROR, message, details);
	}
	
	private static void addMessage(Severity severity, String message, String details) {
		FacesContext fc = FacesContext.getCurrentInstance();
		fc.addMessage(null, newFacesMessage(severity, message, details));
	}
	
	public static void limparMensagens() {
		FacesContext fc = FacesContext.getCurrentInstance();
		if(fc.getMessageList() != null && !fc.getMessageList().isEmpty()){
			Iterator<FacesMessage> iter = fc.getMessages();   
            while (iter.hasNext()) {   
                iter.remove();   
            }   
		}
	}
	
	private static FacesMessage newFacesMessage(Severity severity, String message, String details) {
		return new FacesMessage(severity, message, details);
	}
	
	public static String getMessageKey(String key) {
		String msg;
		try {
			msg = messageBundle.getString(key);
		} catch (Exception e) {
			msg = key;
		}
		return msg;
	}
	
	public static String getInfosKey(String key) {
		String msg;
		try {
			msg = infosBundle.getString(key);
		} catch (Exception e) {
			msg = "";
		}
		return msg;
	}
	
	public static String getResourceKey(String key) {
		String msg;
		try {
			msg = resourceBundle.getString(key);
		} catch (Exception e) {
			msg = key;
		}
		return msg;
	}
}
